package org.lboot.md.controller;

import cn.hutool.core.io.file.FileNameUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.lboot.md.constant.MarkdownConst;
import org.lboot.md.service.MarkdownCtl;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.Map;

/**
 * @author kindear
 * RESTful 接口
 */
@Slf4j
@RestController
@RequestMapping("vditor")
@Api(tags = "MD服务接口")
@AllArgsConstructor
public class MarkdownRestController {
    MarkdownCtl markdownCtl;

    @ApiIgnore
    @PostMapping("callback")
    @ApiOperation(value = "vditor编辑回调",notes = "")
    public Object vditorEditCallback(@RequestBody Map<String,Object> map){
        // 编辑回调处理
        return markdownCtl.editCallback(map);
    }

    public String handle(String url,String fileName){
        // 获取文件类型
        String fileType = FileNameUtil.extName(fileName);
        // 如果是图片
        if (MarkdownConst.IMG_FILE.contains(fileType)){
            return "!["+fileName+"]("+url+")";
        }
        // 如果是音乐
        if (MarkdownConst.MUSIC_FILE.contains(fileType)){
            String t =  "<audio id=\"audio\" controls=\"\" preload=\"none\">\n" +
                    "      <source id=\"mp3\" src=\"${url}\">\n" +
                    "</audio>";
            return t.replace("${url}",url);
        }

        // 其他直接超链接
        return "["+fileName+"]("+url+")";
    }
    @PostMapping("upload")
    @ApiOperation(value = "vditor上传",notes = "")
    public Map<String,Object> vditorUpload(@RequestParam("file") MultipartFile file){
        Map<String,Object> resMap = new HashMap<String,Object>();
        resMap.put("success",true);
        resMap.put("code",200);
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取链接
        String url = markdownCtl.fileUpload(file);
        // 获取预处理
        String html = handle(url,fileName);
        //
        resMap.put("data",html);
        return resMap;
    }


}
